<template>

  <!--头: 引入 CommonHead 子组件-->
  <header class="update-gender-head">
    <CommonHead title="修改用户性别"/>
  </header>

  <br/>

  <!--体: 使用卡片单元格布局修改界面-->
  <section class="update-gender-body">

    <!--单选按钮: 双绑性别-->
    <van-radio-group v-model="gender">

      <!--单元格: 卡片风格-->
      <van-cell-group inset>

        <!--单元格项: 内容，可点击，点击时触发-->
        <van-cell title="♀ 女孩 ♀" clickable @click="updateGender('0')">
          <template #right-icon>
            <van-radio name="0"/>
          </template>
        </van-cell>

        <!--单元格项: 内容，可点击，点击时触发-->
        <van-cell title="♂ 男孩 ♂" clickable @click="updateGender('1')">
          <template #right-icon>
            <van-radio name="1"/>
          </template>
        </van-cell>

        <!--单元格项: 内容，可点击，点击时触发-->
        <van-cell title="不告诉你" clickable @click="updateGender('2')">
          <template #right-icon>
            <van-radio name="2"/>
          </template>
        </van-cell>

      </van-cell-group>

    </van-radio-group>

  </section>

</template>

<script setup>

import CommonHead from "@/components/CommonHead";
import {UPDATE_PERSONAL} from '@/api/user';
import {useStore} from "vuex";
import router from "@/router";
import {onBeforeMount, shallowRef} from "vue";
import {showFailToast, showSuccessToast} from "vant";
import {SUCCESS} from "@/constant";

/* ==================== data ==================== */

// data: Vuex实例，直接使用useStore()会报错
let vuex = useStore();

// data: 用户主键
const userId = sessionStorage.getItem('userId');

// data: 用户性别，转为字符串是为了方便单选按钮切换
let gender = shallowRef(router.currentRoute.value.query['gender'] + "");

/* ==================== method ==================== */

// method: 修改用户性别
async function updateGender(gender) {
  // 异步调用修改用户信息接口
  let result = await UPDATE_PERSONAL({'gender': gender});
  let resp = result['data'];
  if (resp.code === SUCCESS) {
    showSuccessToast("修改成功");
    await router.push("/Personal");
  } else {
    showFailToast(resp.message + ': ' + resp.data);
  }
}

/* ==================== beforeMount ==================== */

// beforeMount: DOM挂载前，判断用户是否登录
onBeforeMount(() => {
  if (!vuex.state['loginFlag']) {
    showFailToast('请先登录');
    setTimeout(() => router.push("/LoginByAccount"), 1000);
  }
});

</script>

<style scoped lang="scss">

</style>